import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getAddressAPI, type addressItem, type ResponseGetAddress } from "../../api/address";

export interface addressState {
    addressList: addressItem[] | [];
    loading: boolean; // 加载状态
    error: string | null; // 错误信息
    addressItem: addressItem | null
}
const initialState: addressState = {
    error: null,
    loading: false,
    addressList: [],
    addressItem: null
}
const addressSlice = createSlice({
    name: 'address',
    initialState,
    reducers: {
        checkedAddress(state, action) {
            state.addressItem = action.payload
        },
        initAddressError(state) {
            state.error = null
        }
    },
    extraReducers(builder) {
        builder
            .addCase(getAddress.pending, ((state) => {
                state.loading = true
                state.error = null
            }))
            .addCase(getAddress.fulfilled, (state, action) => {
                state.addressList = action.payload.data
                state.loading=false
            })
            .addCase(getAddress.rejected, (state, action) => {
                state.loading = false
                state.error = action.payload || '获取用户地址错误'
            })
    },
})

export const getAddress = createAsyncThunk<ResponseGetAddress, void, { rejectValue: string }>('address/getAddress', async (_, { rejectWithValue }) => {
    try {
        const res = await getAddressAPI()
        console.log(res)
        if (res.status !== 200) {
            return rejectWithValue('请求失败')
        }
        if (res.data.code !== 0) {
            return rejectWithValue(res.data.msg || '请求失败')
        }
        return res.data
    } catch (error) {
        return rejectWithValue(error + '')
    }
})



export const { checkedAddress,initAddressError } = addressSlice.actions
export const addressReducer = addressSlice.reducer

